package com.kaibes.im.view.fragment;

import java.util.ArrayList;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Bundle;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ImageSpan;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;
import android.widget.TabHost.TabSpec;
import android.widget.TextView;

import com.kaibes.im.R;
import com.kaibes.im.control.activity.MainActivity;
import com.kaibes.im.model.SocketWorker;
import com.kaibes.im.model.adapter.ChatListviewAdapter;
import com.kaibes.im.model.adapter.ClassicalGridviewAdapter;
import com.kaibes.im.model.adapter.GuideViewpagerAdapter;
import com.kaibes.im.model.hanlder.BaseHandler;
import com.kaibes.im.utils.StaticValuesUtil;
import com.kaibes.im.view.listview.ChatListview;

public class ChatFragment extends KaibesFragment implements OnClickListener {

    public static final int REFRESH_MESSAGE = 1;

    private TextView tvChatFragmentContactName;
    private ChatListview chatListView;
    private EditText etChatFragmentMessage;
    private Button btChatFragmentMessage;
    private ImageButton ibChatFragmentFace, ibChatFragmentEdit,
	    ibChatFragmentMore;

    private TabHost thChatFragmentFace;
    private InputMethodManager inputMethodManager;

    private ViewPager recentlyViewPager;
    private ViewPager classicalViewPager;
    private ImageView[] recentlyPoints;
    private ImageView[] classicalPoints;

    private TabHost tabHost;

    @Override
    public void onCreate(Bundle savedInstanceState) {
	setHandler(new BaseHandler<ChatFragment>(this) {
	    @Override
	    public void handleMessage(Message msg) {
		switch (msg.what) {
		case REFRESH_MESSAGE: {
		    ((ChatListviewAdapter) getData().chatListView.getAdapter())
			    .notifyDataSetChanged();
		    break;
		}
		case KaibesFragment.REFRESH_FRAGMENT:
		    reset();
		    break;
		default:
		    break;
		}
	    }
	});

	super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
	    Bundle savedInstanceState) {
	View rootView = inflater.inflate(R.layout.fragment_chat, container,
		false);
	return rootView;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
	inputMethodManager = (InputMethodManager) getActivity()
		.getSystemService(Context.INPUT_METHOD_SERVICE);

	inRecentlyFaceView();
	inClassicalFaceView();

	tvChatFragmentContactName = (TextView) getView().findViewById(
		R.id.tvChatFragmentContactName);
	chatListView = (ChatListview) getView().findViewById(R.id.chatListView);
	btChatFragmentMessage = (Button) getView().findViewById(
		R.id.btChatFragmentMessage);
	etChatFragmentMessage = (EditText) getView().findViewById(
		R.id.etChatFragmentMessage);
	thChatFragmentFace = (TabHost) getView().findViewById(
		R.id.thChatFragmentFace);
	ibChatFragmentFace = (ImageButton) getView().findViewById(
		R.id.ibChatFragmentFace);
	ibChatFragmentEdit = (ImageButton) getView().findViewById(
		R.id.ibChatFragmentEdit);
	ibChatFragmentMore = (ImageButton) getView().findViewById(
		R.id.ibChatFragmentMore);

	chatListView.setAdapter(new ChatListviewAdapter(getKaibesActivity(),
		getKaibesApplication().getCurentContact()
			.getChatListviewDatas()));
	reset();

	getView().findViewById(R.id.tvChatFragmentTitleBack)
		.setOnClickListener(this);
	getView().findViewById(R.id.tvChatFragmentInformation)
		.setOnClickListener(this);

	btChatFragmentMessage.setOnClickListener(this);
	etChatFragmentMessage.setOnClickListener(this);
	ibChatFragmentFace.setOnClickListener(this);
	ibChatFragmentEdit.setOnClickListener(this);
	ibChatFragmentMore.setOnClickListener(this);

	initTabHost();
	super.onActivityCreated(savedInstanceState);
    }

    @Override
    protected void reset() {
	((ChatListviewAdapter) chatListView.getAdapter())
		.setDatas(getKaibesApplication().getCurentContact()
			.getChatListviewDatas());
	if (getKaibesApplication().getCurentContact() != null) {
	    if (getKaibesApplication().getCurentContact().getRemark()
		    .equals("")) {
		tvChatFragmentContactName.setText(getKaibesActivity()
			.getKaibesApplication().getCurentContact()
			.getNickname());
	    } else {
		tvChatFragmentContactName.setText(getKaibesActivity()
			.getKaibesApplication().getCurentContact()
			.getRemark());
	    }
	}
	refresh(REFRESH_MESSAGE);
    }

    @Override
    public boolean onBackPressed() {
	if (ibChatFragmentEdit.getVisibility() == View.VISIBLE) {
	    ibChatFragmentFace.setVisibility(View.VISIBLE);
	    ibChatFragmentEdit.setVisibility(View.GONE);
	    ibChatFragmentMore.setVisibility(View.VISIBLE);
	    thChatFragmentFace.setVisibility(View.GONE);
	} else {
	    setLastFragment(null);
	    getKaibesActivity().changeFragment(MainFragment.class);
	}
	return false;
    }

    private void initTabHost() {
	tabHost = (TabHost) getView().findViewById(R.id.thChatFragmentFace);
	tabHost.setup();
	tabHost.setOnTabChangedListener(new OnTabChangeListener() {

	    @Override
	    public void onTabChanged(String tabId) {
		etChatFragmentMessage.requestFocus();
		if (tabId.equals("recently")) {
		    resetRecentlyViewPager();
		}

		if (tabId.equals("classical")) {
		    resetClassicalViewPager();
		}
	    }
	});

	TabSpec spec1 = tabHost.newTabSpec("recently");
	TabSpec spec2 = tabHost.newTabSpec("classical");
	TabSpec spec3 = tabHost.newTabSpec("big");

	spec1.setContent(R.id.tabRecentlyFace);
	spec2.setContent(R.id.tabClassicalFace);
	spec3.setContent(R.id.tabBigFace);

	spec1.setIndicator(LayoutInflater.from(getActivity()).inflate(
		R.layout.tab_face_widget_recently,
		(ViewGroup) tabHost.findViewById(R.id.tabRecentlyFace), false));
	spec2.setIndicator(LayoutInflater.from(getActivity()).inflate(
		R.layout.tab_face_widget_classical,
		(ViewGroup) tabHost.findViewById(R.id.tabClassicalFace), false));
	spec3.setIndicator(LayoutInflater.from(getActivity()).inflate(
		R.layout.tab_face_widget_big,
		(ViewGroup) tabHost.findViewById(R.id.tabBigFace), false));

	tabHost.addTab(spec1);
	tabHost.addTab(spec2);
	tabHost.addTab(spec3);

	tabHost.setCurrentTab(1);
    }

    private void inRecentlyFaceView() {
	final int[] ids = { R.id.iv_recently_1, R.id.iv_recently_2 };

	recentlyPoints = new ImageView[2];
	recentlyPoints[0] = (ImageView) getView().findViewById(ids[0]);
	recentlyPoints[1] = (ImageView) getView().findViewById(ids[1]);

	LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
	ArrayList<View> views = new ArrayList<View>();

	views.add(layoutInflater.inflate(R.layout.viewpager_recently_1, null));
	views.add(layoutInflater.inflate(R.layout.viewpager_recently_2, null));

	GuideViewpagerAdapter viewPagerAdapter = new GuideViewpagerAdapter(
		views, getActivity());

	recentlyViewPager = (ViewPager) getView().findViewById(
		R.id.viewpager_recently);
	recentlyViewPager.setAdapter(viewPagerAdapter);
	recentlyViewPager.setOnPageChangeListener(new OnPageChangeListener() {

	    @Override
	    public void onPageSelected(int arg0) {
		recentlyPoints[arg0].setImageResource(R.drawable.face_tip_2);
		recentlyPoints[Math.abs(1 - arg0)]
			.setImageResource(R.drawable.face_tip_1);
	    }

	    @Override
	    public void onPageScrolled(int arg0, float arg1, int arg2) {

	    }

	    @Override
	    public void onPageScrollStateChanged(int arg0) {

	    }
	});

	inRecentlyGridView(views);
    }

    private void inClassicalFaceView() {
	final int[] ids = { R.id.iv_classical_1, R.id.iv_classical_2,
		R.id.iv_classical_3, R.id.iv_classical_4 };

	classicalPoints = new ImageView[4];
	for (int i = 0; i < classicalPoints.length; i++) {
	    classicalPoints[i] = (ImageView) getView().findViewById(ids[i]);
	}

	LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
	ArrayList<View> views = new ArrayList<View>();
	views.add(layoutInflater.inflate(R.layout.viewpager_classical_qq_1,
		null));
	views.add(layoutInflater.inflate(R.layout.viewpager_classical_qq_2,
		null));
	views.add(layoutInflater.inflate(R.layout.viewpager_classical_qq_3,
		null));
	views.add(layoutInflater.inflate(R.layout.viewpager_classical_qq_4,
		null));

	GuideViewpagerAdapter viewPagerAdapter = new GuideViewpagerAdapter(
		views, getActivity());
	classicalViewPager = (ViewPager) getView().findViewById(
		R.id.viewpager_classical);
	classicalViewPager.setAdapter(viewPagerAdapter);
	classicalViewPager.setOnPageChangeListener(new OnPageChangeListener() {

	    @Override
	    public void onPageSelected(int arg0) {
		classicalPoints[arg0].setImageResource(R.drawable.face_tip_2);
		if (arg0 > 0) {
		    classicalPoints[arg0 - 1]
			    .setImageResource(R.drawable.face_tip_1);
		}
		if (arg0 + 1 < classicalPoints.length) {
		    classicalPoints[arg0 + 1]
			    .setImageResource(R.drawable.face_tip_1);
		}
	    }

	    @Override
	    public void onPageScrolled(int arg0, float arg1, int arg2) {
	    }

	    @Override
	    public void onPageScrollStateChanged(int arg0) {
	    }
	});

	inClassicalGridView(
		(GridView) views.get(0).findViewById(
			R.id.gridView_classical_qq_1), 0);
	inClassicalGridView(
		(GridView) views.get(1).findViewById(
			R.id.gridView_classical_qq_2), 20);
	inClassicalGridView(
		(GridView) views.get(2).findViewById(
			R.id.gridView_classical_qq_3), 40);
	inClassicalGridView(
		(GridView) views.get(3).findViewById(
			R.id.gridView_classical_qq_4), 60);
    }

    private void resetRecentlyViewPager() {
	recentlyViewPager.setCurrentItem(0);
	recentlyPoints[0].setImageResource(R.drawable.face_tip_2);
	recentlyPoints[1].setImageResource(R.drawable.face_tip_1);
    }

    private void resetClassicalViewPager() {
	classicalViewPager.setCurrentItem(0);
	classicalPoints[0].setImageResource(R.drawable.face_tip_2);
	classicalPoints[1].setImageResource(R.drawable.face_tip_1);
	classicalPoints[2].setImageResource(R.drawable.face_tip_1);
	classicalPoints[3].setImageResource(R.drawable.face_tip_1);
    }

    private void inRecentlyGridView(ArrayList<View> views) {
	// TODO
    }

    private void inClassicalGridView(GridView gridView, int start) {

	ArrayList<String> faceName = new ArrayList<String>(21);

	for (int i = 0; i < 20; i++) {
	    faceName.add(StaticValuesUtil.faceHashClassicKeys[start + i]);
	}
	faceName.add(StaticValuesUtil.FACE_HASH_DELETE_FACE_NAME);

	gridView.setAdapter(new ClassicalGridviewAdapter(getKaibesActivity(),
		faceName));
	gridView.setOnItemClickListener(new OnItemClickListener() {

	    @Override
	    public void onItemClick(AdapterView<?> parent, View view,
		    int position, long id) {
		if (position != 20) {
		    Bitmap bitmap = BitmapFactory.decodeResource(
			    getResources(), (int) id);
		    ImageSpan imageSpan = new ImageSpan(getKaibesActivity(),
			    bitmap);
		    SpannableString spannableString = new SpannableString("#("
			    + parent.getAdapter().getItem(position) + ")");
		    spannableString.setSpan(imageSpan, 0,
			    spannableString.length(),
			    Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
		    etChatFragmentMessage.append(spannableString);

		} else {
		    KeyEvent keyEvent = new KeyEvent(KeyEvent.ACTION_DOWN,
			    KeyEvent.KEYCODE_DEL);
		    etChatFragmentMessage.onKeyDown(keyEvent.getKeyCode(),
			    keyEvent);
		}
	    }
	});
    }

    @Override
    public void onClick(View v) {
	switch (v.getId()) {
	case R.id.tvChatFragmentTitleBack: {
	    if (ibChatFragmentEdit.getVisibility() == View.VISIBLE) {
		ibChatFragmentFace.setVisibility(View.VISIBLE);
		ibChatFragmentEdit.setVisibility(View.GONE);
		ibChatFragmentMore.setVisibility(View.VISIBLE);
		thChatFragmentFace.setVisibility(View.GONE);
	    }
	    setLastFragment(null);
	    getKaibesActivity().changeFragment(MainFragment.class);
	    break;
	}

	case R.id.tvChatFragmentInformation: {
	    getKaibesActivity().changeFragment(
		    ContactInformationMoreFragment.class);
	    break;
	}

	case R.id.btChatFragmentMessage: {
	    String message = etChatFragmentMessage.getText().toString().trim();

	    if (!message.equals("")) {
		((MainActivity) getActivity()).getKaibesApplication().sendData(
			1,
			SocketWorker.ACTION_MESSAGE,
			getKaibesApplication().getCurentContact()
				.getContactname(), message);
		getKaibesApplication()
			.getCurentContact()
			.addChatListviewData(message,
				getKaibesApplication().getUserInformationData());
		refresh(REFRESH_MESSAGE);
	    }

	    etChatFragmentMessage.setText("");
	    break;
	}

	case R.id.etChatFragmentMessage: {
	    ibChatFragmentEdit.performClick();
	    break;
	}

	case R.id.ibChatFragmentFace: {
	    ibChatFragmentFace.setVisibility(View.GONE);
	    ibChatFragmentEdit.setVisibility(View.VISIBLE);
	    ibChatFragmentMore.setVisibility(View.VISIBLE);
	    thChatFragmentFace.setVisibility(View.VISIBLE);
	    inputMethodManager.hideSoftInputFromWindow(getActivity()
		    .getCurrentFocus().getWindowToken(),
		    InputMethodManager.HIDE_NOT_ALWAYS);
	    break;
	}

	case R.id.ibChatFragmentEdit: {
	    inputMethodManager.toggleSoftInput(0,
		    InputMethodManager.SHOW_IMPLICIT);

	    ibChatFragmentFace.setVisibility(View.VISIBLE);
	    ibChatFragmentEdit.setVisibility(View.GONE);
	    ibChatFragmentMore.setVisibility(View.VISIBLE);
	    thChatFragmentFace.setVisibility(View.GONE);

	    resetRecentlyViewPager();
	    resetClassicalViewPager();
	    break;
	}

	case R.id.ibChatFragmentMore: {
	    ibChatFragmentFace.setVisibility(View.VISIBLE);
	    ibChatFragmentEdit.setVisibility(View.VISIBLE);
	    ibChatFragmentMore.setVisibility(View.GONE);
	    thChatFragmentFace.setVisibility(View.VISIBLE);

	    inputMethodManager.hideSoftInputFromWindow(getActivity()
		    .getCurrentFocus().getWindowToken(),
		    InputMethodManager.HIDE_NOT_ALWAYS);
	    break;
	}

	default:
	    onBackPressed();
	    break;
	}
    }

}
